package com.zr.inquiry.service.imp;

import com.zr.inquiry.mapper.InquiryMapper;
import com.zr.inquiry.meiju.CurrencyCodeEnum;
import com.zr.inquiry.meiju.IsTaxEnum;
import com.zr.inquiry.meiju.StatusEnum;
import com.zr.inquiry.meiju.TypeEnum;
import com.zr.inquiry.pojo.*;
import com.zr.inquiry.service.InquiryService;
import com.zr.util.AllRecords;
import com.zr.util.ResultVo;
import com.zr.util.ResultVoBuilder;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.validation.Valid;
import java.util.*;

/**
 * Created by 陈紫陌 on 2019-10-09.
 */
@Service
@Transactional
public class InquiryServiceImpl implements InquiryService {

    @Autowired
    private InquiryMapper inquiryMapper;

    @Override
    public ResultVo addInquiry(@Valid InquiryAddVo inquiryAddVo) {

        //验证
        ResultVo resultVo = vaildate(inquiryAddVo);
        if (!resultVo.getSuccess()){
            return resultVo;
        }
        //入库主表数据
        InquiryTotal inquiryTotal = new InquiryTotal();
        BeanUtils.copyProperties(inquiryAddVo,inquiryTotal);
        Date nowDate = new Date();
        inquiryTotal.setCreatorName("张三");
        inquiryTotal.setCreateTime(nowDate);
        inquiryTotal.setUpdateName("张三");
        inquiryTotal.setUpdateTime(nowDate);
        inquiryTotal.setRequestForQuotationId(UUID.randomUUID().toString());
        inquiryMapper.addInquiryTotal(inquiryTotal);
        //入库备件明信息
        List<InquirySpareDetail> inquirySpareDetailList = inquiryAddVo.getInquirySpareDetailList();
        for (InquirySpareDetail inquirySpareDetail:inquirySpareDetailList) {
            inquirySpareDetail.setInquiryId(inquiryTotal.getId());
        }
        inquiryMapper.addInquirySparePartDetail(inquirySpareDetailList);
        //入库供应商备件信息
        List<InquirySupplirDetail> inquirySupplirDetailList = inquiryAddVo.getInquirySupplirDetailList();
        for (InquirySupplirDetail inquirySupplirDetail : inquirySupplirDetailList) {
            inquirySupplirDetail.setInquiryId(inquiryTotal.getId());
        }
        inquiryMapper.addInquirySupplirDetail(inquirySupplirDetailList);

        return ResultVoBuilder.success();
    }

    private ResultVo vaildate(@Valid InquiryAddVo inquiryAddVo) {
        /**
         * 6.验证备件是否存在，并且提示那个备件已经存在了；
         * 7.验证备件是否重复，并且提示那个备件重复了；
         * 8.验证备件是否存在可以生产它的供应商，并且提示用户哪个供应商可以生产它；
         * 9.验证询价数量是否为0；
         * 10.验证供应商是否存在，并且提示那个供应商已经存在了；
         * 11.验证是否重复，并且提示那个供应商重复了；
         * 12.验证供应商是否存在可以生产的备件，并且提示用户哪个备件它可以生产；
         * 13.验证备件集合不能为空；
         * 14.验证供应商集合不能为空；
         */
        ResultVo resultVo = vaildateTotal(inquiryAddVo);
        if (!resultVo.getSuccess()){
            return resultVo;
        }
        ResultVo resultVo1 = vaildateDetail(inquiryAddVo);
        if (!resultVo1.getSuccess()){
            return resultVo1;
        }
        return  ResultVoBuilder.success();

    }

    private ResultVo vaildateTotal(@Valid InquiryAddVo inquiryAddVo) {

        //* 1.验证法人是否存在；
        LegalPersonVo legalPersonVo = inquiryMapper.queryLegalPersionById(inquiryAddVo.getLegalPersonId());
        if (legalPersonVo==null){
            return ResultVoBuilder.error("法人信息不存在！");
        }
        //* 2.验证询价类型是否存在；
        if (TypeEnum.getName(inquiryAddVo.getType())==null){
            return ResultVoBuilder.error("询价类型不存在！");
        }
        // * 3.验证币别是否存在；
        if (CurrencyCodeEnum.getName(inquiryAddVo.getType())==null){
            return ResultVoBuilder.error("币别不存在！");
        }
        //* 4.验证是否含税是否存在；
        if (IsTaxEnum.getName(inquiryAddVo.getType())==null){
            return ResultVoBuilder.error("是否含税不存在！");
        }
        //* 5.验证开始日期是否在结束日期之前；
        if (inquiryAddVo.getStartTime().getTime()<inquiryAddVo.getEndTime().getTime()){
            return ResultVoBuilder.error("开始日期必须在结束日期之前！");
        }


        return ResultVoBuilder.success();
    }

    private ResultVo vaildateDetail(@Valid InquiryAddVo inquiryAddVo) {
        //备件集合
        List<InquirySpareDetail> inquirySpareDetailList = inquiryAddVo.getInquirySpareDetailList();
        List<String> codeList = new ArrayList<>();
        List<String> repeatCodeList = new ArrayList<>();
        List<String> repeatNowCodeList = new ArrayList<>();
        //验证备件是否重复，并且提示那个备件重复了；
        for (InquirySpareDetail inquirySpareDetail:inquirySpareDetailList
             ) {
            /**if (inquirySpareDetail.getInquiryQty()==0||inquirySpareDetail.getInquiryQty()==null){
                codeList.add(inquirySpareDetail.getSpareCoding());
            }*/
            codeList.add(inquirySpareDetail.getSpareCoding());

        }
        for (String code:codeList
             ) {
            if (repeatCodeList.contains(code)) {
                repeatNowCodeList.add(code);

            }else {
                repeatCodeList.add(code);
            }
        }
        if (!repeatNowCodeList.isEmpty()){
            return ResultVoBuilder.error("存在重复的备件编码，重复的备件编码为："+repeatNowCodeList);
        }

        //验证是否存在
        List<String> codes = inquiryMapper.querySparePartByList(codeList);
        if (codes.size()!=codeList.size()){
            codeList.removeAll(codes);
            return ResultVoBuilder.error("不存在的备件编码"+codeList);

        }
        //验证备件是否存在合法的供应商
        List<InquirySupplirDetail> inquirySupplirDeatilList = inquiryAddVo.getInquirySupplirDetailList();
        List<String> supplierCodeList = new ArrayList<>();
        for (InquirySupplirDetail inquirySupplierDeatil: inquirySupplirDeatilList
             ) {
            supplierCodeList.add(inquirySupplierDeatil.getVendorCode());
        }
        //1.根据备件集合查询出这些备件对应的供应商信息
        List<SpareSupplier> spareSupplierList = inquiryMapper.querySpareSupplierByCodeList(codeList);
        for (String code:codeList
             ) {
            //根据中间表找出的供应商集合
            List<String> vendorList = new ArrayList<>();
            for (SpareSupplier spareSupplier: spareSupplierList
                 ) {
                if (code.equals(spareSupplier.getSpareCoding())){
                    vendorList.add(spareSupplier.getVendorCode());
                }
            }
            if (Collections.disjoint(supplierCodeList,vendorList)){
                return ResultVoBuilder.error("备件编码："+code+"不存在合法的供应商，它的合法供应商为："+vendorList);
            }

        }
        return ResultVoBuilder.success();
    }

    /**
     * 查询接口实现
     * @param id
     * @return
     */
    @Override
    @Transactional
    public ResultVo queryById(Integer id) {
        if (id==null){
            return ResultVoBuilder.error("查看时Id不能为空");
        }
        InquiryTotal inquiryTotal = inquiryMapper.queryById(id);
        if (inquiryTotal == null){
            return ResultVoBuilder.error("查看对象不存在！");
        }
        inquiryTotal.setCurrencyCodeName(CurrencyCodeEnum.getName(inquiryTotal.getCurrencyCode()));
        inquiryTotal.setIsTaxName(IsTaxEnum.getName(inquiryTotal.getIsTax()));
        inquiryTotal.setTypeName(TypeEnum.getName(inquiryTotal.getType()));

        List<InquirySpareDetail> inquirySpareDetailList = inquiryMapper.querySparePartByTotalId(id);
        List<InquirySupplirDetail> inquirySupplirDetailList= inquiryMapper.querySupplirByTotalId(id);
        inquiryTotal.setInquirySpareDetailList(inquirySpareDetailList);
        inquiryTotal.setInquirySupplirDetailList(inquirySupplirDetailList);
        return ResultVoBuilder.success(inquiryTotal);
    }

    @Override
    @Transactional
    public ResultVo updateInquiry(@Valid InquiryUpdateVo inquiryUpdateVo) {
        InquiryTotal inquiryTotal2 = inquiryMapper.queryById(inquiryUpdateVo.getId());
        if (inquiryTotal2 == null){
            return ResultVoBuilder.error("修改对象不存在！");
        }
        //业务逻辑验证
        //验证
        InquiryAddVo inquiryAddVo = new InquiryAddVo();
        BeanUtils.copyProperties(inquiryUpdateVo,inquiryAddVo);
        ResultVo resultVo = vaildateTotal(inquiryAddVo);
        if (!resultVo.getSuccess()){
            return resultVo;
        }
        //入库
        //入库主表数据
        InquiryTotal inquiryTotal = new InquiryTotal();
        BeanUtils.copyProperties(inquiryUpdateVo,inquiryTotal);
        Date nowDate = new Date();
        //inquiryTotal.setCreatorName("张三");
        //inquiryTotal.setCreateTime(nowDate);
        inquiryTotal.setUpdateName("张三");
        inquiryTotal.setUpdateTime(nowDate);
        //inquiryTotal.setRequestForQuotationId(UUID.randomUUID().toString());
        inquiryMapper.updateInquiryTotal(inquiryTotal);
        //入库备件明信息
        List<InquirySpareDetail> inquirySpareDetailList = inquiryUpdateVo.getInquirySpareDetailList();
        for (InquirySpareDetail inquirySpareDetail:inquirySpareDetailList) {
            inquirySpareDetail.setInquiryId(inquiryTotal.getId());
        }
        inquiryMapper.deleteSparePartByTotalId(inquiryTotal.getId());
        inquiryMapper.addInquirySparePartDetail(inquirySpareDetailList);
        //入库供应商备件信息
        List<InquirySupplirDetail> inquirySupplirDetailList = inquiryUpdateVo.getInquirySupplirDetailList();
        for (InquirySupplirDetail inquirySupplirDetail : inquirySupplirDetailList) {
            inquirySupplirDetail.setInquiryId(inquiryTotal.getId());
        }
        inquiryMapper.deleteSupplierByTotalId(inquiryTotal.getId());
        inquiryMapper.addInquirySupplirDetail(inquirySupplirDetailList);
        return ResultVoBuilder.success();
    }

    @Override
    public ResultVo queryPage(@Valid InquirySelectVo inquirySelectVo) {
        //1.查询数据
        List<InquiryTotal> inquiryTotals = inquiryMapper.queryPage(inquirySelectVo);
        for (InquiryTotal inquiryTotal:inquiryTotals
             ) {
            inquiryTotal.setInquiryStatusName(StatusEnum.getName(inquiryTotal.getInquiryStatus()));
        }
        //2.查询数量
        int count = inquiryMapper.queryCount(inquirySelectVo);

        AllRecords allRecords = new AllRecords();
        allRecords.setDataList(inquiryTotals);
        allRecords.setPageIndex(inquirySelectVo.getPageIndex());
        allRecords.setPageSize(inquirySelectVo.getPageSize());
        allRecords.setTotalNumber(count);
        allRecords.resetTotalPage(count);

        return ResultVoBuilder.success(allRecords);
    }
}
